import cn.edu.dgut.Entity.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String head_img = null;

        Map<String, String> formMap = new HashMap<String, String>();    //保存文本域数据进 formMap 中
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
            for (FileItem fi : list ) {
                //判断是否是文本域
                if(fi.isFormField()){
                    String fieldName = fi.getFieldName();
                    formMap.put(fieldName,fi.getString("utf-8"));       //保存文本域数据进 formMap 中
                }else {
                    if(fi.getSize()!=0){ //判断文件上传框是否选择了图片
                        head_img = fi.getName();
                        String path = getServletContext().getRealPath("/uploadImages");
                        InputStream is = fi.getInputStream();
                        FileOutputStream os = new FileOutputStream(new File(path, head_img));
                        IOUtils.copy(is,os);
                        os.close();
                        is.close();
                        fi.delete();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if(head_img==null){    //head_img==null时，用户没有上传头像，则设置为默认头像 boy.png
            head_img="boy.png";
        }
        try{
            EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
            //生成工号 id+20190000
            String jpql = "select max(u.id) from User u";
            Query query =   em.createQuery(jpql,Integer.class);
            Integer num = (Integer)query.getSingleResult();
            if(num==null){
                num =0;
            }
            num+=20190001;//生成工号 id+20190000
            String user_number = num.toString();
            User user = new User(user_number,formMap.get("name"),formMap.get("phone_number"),formMap.get("email"),formMap.get("password"),head_img,null,null,null,null,null);
            em.persist(user);

            //保存登录信息，设置session并重定向到用户信息页面info.jsp
            Map<String, String> info = new HashMap<String, String>();
            info.put("user_number", user_number);
            info.put("name", formMap.get("name"));
            info.put("faculty_title", "NULL");
            info.put("group", "NULL");
            HttpSession session = request.getSession(true);
            session.setAttribute("isLogin", info);
            response.sendRedirect("/info.jsp");
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
